<?php
class CategoryController extends Vnf_Controller_Action {
    function init() {

        $this->view->maximizeWin = true; // maximize window after popup
        $this->view->winWidth = 640; // default width of window
        $this->view->winHeight = 480; // default height of window
        parent::init();

        $this->setLayout('content');

        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');

        $this->view->currentController = $this->_request->getControllerName();
        $this->view->objName = "Category"; // class name of Model
        $objName = $this->view->objName;
        $this->view->objModel = $obj = new $objName();

        //        $this->view->pk = $obj->getPrimaryKey();
    }

    public function indexAction() {
//        Zend_Layout::getLayout('content');
    }

    public function dataAction() {
        $obj = $this->view->objModel;

        $records = $obj->getRecords();

        //        print_r($records);die;
        //        $records = $records->toArray();

        $result = array();
        $newName = "1";
        $$newName = 0;
        $flagRoot = true;
        $defaultParent = '';
        $parent = '';
        foreach ($records as $row) {
            // these line use to get path of category
            $newID = $row['category_id'];
            $parentID = $row['parent'];
            if ($row['parent'] == 0 || $row['parent'] == null)
            $$newID = $row['admin_title'];
            else $$newID = $$parentID . ' >> ' . $row['admin_title'];

            // replace current category from path

            $tmp['path'] = str_replace(">> {$row['admin_title']}", "", $$newID);
            //            $$newID = $row['admin_title'];
            $tmp['_id'] = $row['category_id'];
            $tmp['parent'] = $row['parent'];
            $tmp['admin_title'] = $row['admin_title'];
            $tmp['status'] = $row['status'];
            $tmp['_lft'] = $row['left'];
            $tmp['_rgt'] = $row['right'];
            $tmp['_level'] = $row['level'];
            $tmp['main_menu'] = $row['main_menu'];
            $tmp['template_id'] = $row['template_id'];
            $tmp['action'] =  "<span style='cursor:pointer;color:green;' onclick='MyDesktop.CategoryManagement.editCategory();'>Edit</span>";
            $tmp['action'] .=  " - <span style='cursor:pointer;color:red;' onclick='MyDesktop.CategoryManagement.deleteCategory();'>Delete</span>";

            if($row['left'] == ($row['right'] - 1)) {
                $tmp['_is_leaf'] = 'true';
            } else {
                $tmp['_is_leaf'] = 'false';
            }
            $result[] = $tmp;
            $flagRoot = false;
        }

        $results = array(
            'success' => true,
            'total' => count($records),
            'data' => $result
        );



        echo Zend_Json::encode($results);die;
    }

    public function listAllAction() {
        $obj = $this->view->objModel;

//        $records = $obj->fetchAll();
        $records = $obj->getRecordsAsFolder();

//        $records = $records->toArray();

        $total = count($records);

        $results = array(
            'total' => $total,
            'results' => $records
        );

        echo Zend_Json::encode($results);die;
    }

    public function deleteAction() {
        $id = (int)$this->getRequest()->getParam('id', -1);
        $result = array();
        if($id > 0) {
            $obj = $this->view->objModel;
            $pk = $obj->getPrimaryKey();

            $obj->delete("'$id'");
            $result['success'] = true;
        }

        $strResult = Zend_Json::encode($result);
        echo $strResult;die;
    }

    public function saveAction() {
        $pk = $this->view->pk;

        $id = (int)$this->getRequest()->getParam("_id", -1);

        $params = $this->_request->getParams();
        $data = array(
            'admin_title' => @$params['admin_title'],
                    'template_id' => @$params['template_id'],
                    'main_menu' => @$params['main_menu'],
        //            'right' => @$params['right'],
            'status' => @$params['status'],
        );

        $obj = $this->view->objModel;

        $root = $obj->getRoot();
        //        print_r($root);die;

        $rootId = $root->category_id;


        $result = array();
        $result['success'] = false;
        if ($id > 0) { // update
            try {
                // save to DB
                $where = "`category_id` = $id";
                $obj->update($data, $where);

                // update parent
                $currentCategory = $obj->getCategoryById($id);
                $currentParent = $currentCategory->parent;
                if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '' && $params['parent'] != $currentParent) {
                    echo "/*<pre>";
                    echo "curr - " . $currentParent;
                    echo "\r\n";
                    echo "new - " . $params['parent'];
                    echo "</pre>*/";
                    $obj->move($id, $params['parent']);
                }

                //                $newParent

                $result['success'] = true;
                $result['message'] = $this->view->translate->_("Save successfull.");
            } catch (Exception $ex){
                $result['success'] = false;
                $result['message'] = $this->view->translate->_("Can't save to DB.") . "<br>" . $ex->getMessage();
            }
        } else { // add
            try {
                if (isset($params['parent']) && $params['parent'] != 0 && $params['parent'] != '')
                $data['parent'] = $params['parent'];
                else $data['parent'] =$rootId;
                $obj->insert($data);
                $result['success'] = true;
                $result['message'] = $this->view->translate->_("Insert successfull.");
            } catch(Exception $ex) {
                $result['message'] = $this->view->translate->_("Can't insert to DB") . "<br>" . $ex->getMessage();
            }
        }
        $strResult = Zend_Json::encode($result);
        echo $strResult;die;
    }

    public function prepareAddAction() {
        // get parent of node
        $this->view->pid = $pid = $this->_getParam("pid", 0);

        $objCategory = new Category();
        $root = $objCategory->getRoot();
        if ($pid > 0) {
            // get path fron root to parent node
            $allParents = $objCategory->getPath($pid);
            $strParent = "";
            if (count($allParents) > 0) {
                foreach ($allParents as $row) {
                    if ($row->left != 1)
                       $strParent .= $strParent==""?$row->admin_title:" >> ".$row->admin_title;
                }
            }
            // assign string path of parent to view layer
            $this->view->strParent = $strParent;
        }
        $this->view->rootId = $root['category_id']; // default width of window
        $this->view->winWidth = 500; // default width of window
        $this->view->winHeight = 250; // default height of window
    }

    public function addProcessAction() {
        $parentId = $this->_getParam("parentid", 0);
        $nodeName = $this->_getParam("name", "");

        $obj = new Category();

        $data = array(
            'admin_title' => $nodeName,
            'parent' => $parentId,
            'status' => 1
        );

        $result = array();
        $result['success'] = false;
        try {
            $obj->insert($data);
            $result['success'] = true;
            $result['message'] = $this->view->translate->_("Insert successfull.");
        } catch(Exception $ex) {
            $result['message'] = $this->view->translate->_("Can't insert to DB") . "<br>" . $ex->getMessage();
        }

        $strResult = Zend_Json::encode($result);
        echo $strResult;die;

    }
}